/*
 * TaskThread.h
 *
 *  Created on: 2020年8月22日
 *      Author: chuanjiang.zh
 */

#ifndef TASKTHREAD_H_
#define TASKTHREAD_H_

#include "BasicType.h"
#include "TThread.h"
#include <functional>
#include <deque>
#include <mutex>
#include "TEvent.h"
#include "PollTimerQueue.h"

namespace comn
{


class TaskThread : public comn::Thread
{
public:
	typedef std::function< void () >	Task;
	typedef std::deque< Task >			TaskQueue;

	typedef std::function< void (int) >	TimerTask;

	enum Constant
	{
		IDLE_DURATION = 1000 * 7,		/// millisecond
		OVERRUN_TIME  = 1000,			/// millisecond
		MAX_QUEUE_SIZE = 2000,
		TIMER_DEGREE   = 500,	/// ms
	};

public:
	TaskThread();
	virtual ~TaskThread();

	void post(Task task);
	void clearTask();

	int addTimer(uint32_t ms, TimerTask task);
	int addElapse(uint32_t ms, TimerTask task);

	void cancelTimer(int tid);
	void clearTimer();

	virtual void postEvent();
	virtual bool timedwait(int ms);

	size_t getQueueSize();
public:
	static int64_t getTime();

protected:
	virtual void onIdle();

	virtual int run();
	virtual void doStop();

private:
	TaskThread(const TaskThread&) = delete;
	TaskThread& operator = (const TaskThread&) = delete;

protected:
	bool fetchAndHandle();
	bool fetchAndHandle(int64_t& curTime);
	bool fetchTask(Task& task);

	int poll();

protected:
	std::mutex		m_taskMutex;
	TaskQueue		m_taskQueue;

	PollTimerQueue*	m_timerQueue;

	comn::Event     m_eventTask;

	int		m_timerDegree;

};


}

#endif /* TASKTHREAD_H_ */
